import { Component, OnInit, Input, EventEmitter, Output, ChangeDetectorRef } from "@angular/core";
import { IonicPage, NavController, Navbar, NavParams } from "ionic-angular";
import { StepComponentProperty } from "../step/step.component";
import { DistrictService } from "../../models/services/district.service";
import { UserDto } from "../../../shared/models/dto/user.dto";
import { BillDto } from "../../../shared/models/dto/bill.dto";
import { WorkOrderDto } from "../../../shared/models/dto/work-orders.dto";
import { DistrictDto } from "../../../shared/models/dto/district.dto";
import { CurdService } from "../../../shared/models/services/curd.service";
import { FlowPathData } from "./flow-path-data";
import { WorkOrderType, WorkOrderStatus } from "../../models/transform/work-order";
import { UtilsService } from "../../services/utils.services";

@Component({
    selector: 'detail-step-component',
    templateUrl: './detail-step.component.html',
})


export class DetailStepComponent  {

    hidde = true;
    UserObj: any = {
      areaName: ''
    };
    billList = {
      arrears: [],
      payments: []
    };
    // userNo: string ;
    resBillList: any;
    userId: string ;
    chargeLevel: number;
    chargeTimesOne: number;
    chargeTimesTwo: number;
    chargeTimesThree: number;
    noticeID: string;
    workOrderID: string;
    isShow: boolean = true;
    type: number;
    workOrderStatus: string;
    isSettle: number;
    payDate: string;
    noticeTime: string;
    attachmentId: string;
    ThrumnailId: string;
    workDate: any;
    chargeAmount: number;
    chargemonthList = [];
    chargemonth: any;
    districtId: string;
    workDateLength: number;

    detailStepList = [];
    arrearsList = [];
    monthList = [];

    @Input('UserId') userNo: any;
    @Input('chargeDetailId') chargeDetailId: any;

    // tslint:disable-next-line:no-input-rename
    // @Input('detailStepList') detailStepList: any;

    // @Output('seeNoticeDetail') noticeDetail = new EventEmitter<any>();

    // @Output('seeStopPowerApplication') stopPowerApplication = new EventEmitter<any>();

    // @Output('seePowerFailureDetail') powerFailureDetail = new EventEmitter<any>();


    constructor(
      public districtService: DistrictService,
      public ref: ChangeDetectorRef,
      public navCtrl: NavController,
      public curdService: CurdService,
      public utilsService: UtilsService
        ) {
        // TODO

    }

    ionViewDidEnter() {
      //
      // this.getFlowPath();
    }

    ngOnInit(): void {
        //
      this.getFlowPath();
    }

    getFlowPath() {
      let level = 1;
      this.curdService.fetchByCondition(UserDto, {and: {id: this.userNo}}).then((res) => {
        let result = res["results"][0];
        this.UserObj = result;
        this.userId = result.id;
        this.districtId = result.districtId;
        this.chargeAmount = result.totalUnPaidAmount;
        console.log(JSON.stringify(this.UserObj));
        this.curdService.fetchByCondition(BillDto, {and: {userId: this.userId}}).then((data) => {
          this.billList.arrears = [];
          this.billList.payments = [];
          this.arrearsList = [];
          this.detailStepList = [];
          this.resBillList = data["results"];
          for (let i = 0; i < this.resBillList.length; i++ ) {
            if ( this.resBillList[i].isSettle === 0 ) {
              let arrears = this.resBillList[i];
              let theMonth = this.resBillList[i].month;
              this.monthList.push(theMonth);
              this.arrearsList.push(arrears);
            } else {
              let  payments = this.resBillList[i];
              this.billList.payments.push( payments);
            }
          }
          if (this.billList.arrears.length > 1) {
            // tslint:disable-next-line:only-arrow-functions
            this.monthList.sort(function(a, b) {return a - b; }).reverse();
            this.monthList.forEach((month) => {
              this.resBillList.arrears.forEach((bill) => {
                if (month === bill.month) {
                  this.billList.arrears.push(bill);
                }
              });
            });
          } else {
            this.billList.arrears = this.arrearsList;
          }
          

          // console.log(JSON.stringify(this.billList.arrears));
          this.billList.arrears.forEach((item, index) => {

            this.chargeLevel = item.chargeLevel;
            this.isSettle = item.isSettle;
            this.noticeTime = item.noticeUploadTime;
            this.attachmentId = item.attachmentId;

            if (index === 0 ) {
              this.chargemonth = item.month;
              if ( item.chargeLevel === 1) {
                this.detailStepList.unshift( { chargeTimes: item.chargeTimesOne, chargeAmount: this.chargeAmount,
                  chargeLevelDes: item.month + "月一级催费次数", stepProp: 2, button: 0});
              }

              if (item.chargeLevel > 1) {
                this.detailStepList.unshift( { chargeTimes: item.chargeTimesOne, chargeAmount: this.chargeAmount,
                  chargeLevelDes: item.month + "月一级催费次数", stepProp: 1, button: 0});
              }

              if ( item.chargeLevel === 2 && item.noticeUploadTime === null) {
                this.detailStepList.unshift( { chargeTimes: item.chargeTimesTwo, chargeAmount: this.chargeAmount,
                  chargeLevelDes: item.month + "月二级催费次数", stepProp: 2, button: 0});
              }

              if (item.chargeLevel > 2 || (item.chargeLevel === 2 && item.noticeUploadTime != null)) {
                this.detailStepList.unshift( { chargeTimes: item.chargeTimesTwo, chargeAmount: this.chargeAmount,
                  chargeLevelDes: item.month + "月二级催费次数", stepProp: 1, button: 0});
              }

              if ( item.chargeLevel === 2 && item.noticeUploadTime != null) {
                this.detailStepList.unshift( { chargeTimes: '', chargeAmount: this.chargeAmount,
                  chargeLevelDes: '已粘贴' + item.month + "月二级通知单", stepProp: 2, button: 1});
              }

              if ( item.chargeLevel > 2 && item.noticeUploadTime !== null) {
                this.detailStepList.unshift( { chargeTimes: '', chargeAmount: this.chargeAmount,
                  chargeLevelDes: '已粘贴' + item.month + "月二级通知单", stepProp: 1, button: 1});
              }
            }
            if (index > 1) {
              this.chargemonthList.push(item.month);
            }
            // console.log('1212' + JSON.stringify(this.detailStepList));
          });
          if (this.chargeLevel === 3) {
            this.curdService.fetchByCondition(WorkOrderDto, {and: {userId: this.userId, chargeDetailId: this.chargeDetailId}}).then((elem) => {
              if (elem["results"].length > 0) {
                let resWorkData = elem["results"];
                console.log('1234567890' + JSON.stringify(resWorkData));
                for (let i = 0; i < resWorkData.length; i++) {
                  if (resWorkData[i].type === WorkOrderType.POWERCUT) {
                    let resData = resWorkData[i];
                    this.type = resData.type;
                    this.workOrderStatus = resData.workOrderStatus;
                    this.workDate = resData;
                    this.workDateLength = elem["results"].length;
                    this.detailStepList.unshift( { chargeTimes: '', chargeAmount: this.chargeAmount,
                      chargeLevelDes: this.chargemonth + "月三级催费", stepProp: 1, button: 0});

                    // if (this.chargemonthList.length > 0) {
                    //   this.chargemonthList.forEach( (item, index) => {
                    //     if (resData.type === WorkOrderType.POWERCUT && resData.workOrderStatus === WorkOrderStatus.TO_BE_APPROVED ) {
                    //       this.detailStepList.unshift( { chargeTimes: '', chargeAmount: this.chargeAmount,
                    //       chargeLevelDes: item + "月三级催费", stepProp: 1, button: 0});
                    //     } else {
                    //       if (index === (this.chargemonthList.length - 1)) {
                    //         this.detailStepList.unshift( { chargeTimes: '', chargeAmount: this.chargeAmount,
                    //       chargeLevelDes: item + "月三级催费", stepProp: 2, button: 0});
                    //       } else {
                    //         this.detailStepList.unshift( { chargeTimes: '', chargeAmount: this.chargeAmount,
                    //       chargeLevelDes: item + "月三级催费", stepProp: 1, button: 0});
                    //       }
                          
                    //     }
                    //   });
                    // }

                    if (resData.type === WorkOrderType.POWERCUT && resData.workOrderStatus === WorkOrderStatus.TO_BE_APPROVED ) {
                      this.detailStepList.unshift( { chargeTimes: '', chargeAmount: this.chargeAmount,
                        chargeLevelDes:  "待审核停电申请", stepProp: 2, button: 2});
                    }
                    if (resData.type === WorkOrderType.POWERCUT && resData.workOrderStatus !== WorkOrderStatus.TO_BE_APPROVED ) {
                      this.detailStepList.unshift( { chargeTimes: '', chargeAmount: this.chargeAmount,
                        chargeLevelDes:  "待审核停电申请", stepProp: 1, button: 2});
                    }
                    if (resData.type === WorkOrderType.POWERCUT && resData.workOrderStatus === WorkOrderStatus.APPROVED ) {
                      this.detailStepList.unshift( { chargeTimes: '', chargeAmount: this.chargeAmount,
                        chargeLevelDes:  "待停电", stepProp: 2, button: 0});
                    }
                    if (resData.type === WorkOrderType.POWERCUT && resData.workOrderStatus === WorkOrderStatus.EXECUTED ) {
                      this.detailStepList.unshift( { chargeTimes: '', chargeAmount: this.chargeAmount,
                        chargeLevelDes:  "待停电", stepProp: 1, button: 0});
                    }
                    if (resData.type === WorkOrderType.POWERCUT && resData.workOrderStatus === WorkOrderStatus.EXECUTED && this.isSettle === 0 ) {
                      this.detailStepList.unshift( { chargeTimes: '', chargeAmount: this.chargeAmount,
                        chargeLevelDes:  "已停电", stepProp: 2, button: 3});
                    }
                    if (resData.type === WorkOrderType.POWERCUT && resData.workOrderStatus === WorkOrderStatus.EXECUTED && this.isSettle !== 0 ) {
                      this.detailStepList.unshift( { chargeTimes: '', chargeAmount: this.chargeAmount,
                        chargeLevelDes:  "已停电", stepProp: 1, button: 3});

                      this.detailStepList.unshift( { chargeTimes: '', chargeAmount: this.chargeAmount,
                        chargeLevelDes:  "已缴费", stepProp: 2, button: 0});
                    }
                  } else {
                    if (i === resWorkData.length - 1) {
                      this.detailStepList.unshift( { chargeTimes: '', chargeAmount: this.chargeAmount,
                        chargeLevelDes: this.chargemonth + "月三级催费", stepProp: 2, button: 0});
                    }

                  }
                }
                // this.workOrderID = resData.id;

                console.log('33333' + JSON.stringify(this.detailStepList));

              } else {
                this.detailStepList.unshift( { chargeTimes: '', chargeAmount: this.chargeAmount,
                  chargeLevelDes: this.chargemonth + "月三级催费", stepProp: 2, button: 0});
              }
              // 如果是复电流程
              this.getResumptionFlowPath(elem["results"]);
            } );
          }
        });
        // console.log(result.districtId);
        this.curdService.fetchByCondition(DistrictDto, { and: {id: this.districtId}}).then( (resData) => {
          if (resData["results"].length > 0) {
            this.UserObj.areaName = resData["results"][0].name;
          } else {
            this.UserObj.areaName = '';
          }
          console.log('stopPower' + JSON.stringify(this.UserObj));
        });

      });
    }


    getResumptionFlowPath(data: Array<object>) {
      switch (data.length) {
        case 0 : break;
        case 1 : this.getPowerStatus(data); break;
        case 2 : this.getRecoverStatus(data); break;
        default : break;
      }
    }

    getPowerStatus(dataArray: Array<object>) {
        let data = dataArray[0];
        if (this.chargeAmount > 0) {
          return;
        }
        for (let key in FlowPathData.data) {
          if (key === data["workOrderStatus"]) {
            let curStatus = FlowPathData.data[key];
            curStatus["stepProp"] = 2;
            if (key === "powerCutAlready") {
              curStatus["resumptionTime"] = true;
            }
            this.detailStepList.unshift(curStatus);
            break;
          } else {
            // remove 审核不通过
            if (key === "recoverAuditNotPassed") {
              continue;
            }
            this.detailStepList.unshift(FlowPathData.data[key]);
          }
        }
    }

    getRecoverStatus(dataArray: Array<object>) {
      if (!Array.isArray(dataArray)) {
        dataArray = Array.from(dataArray);
      }
      let dataTem = dataArray.filter((item) => {
        return item["type"] === WorkOrderType.POWERRECOVERY;
      });
      if (!dataTem) {
        return;
      }
      this.getPowerStatus(dataTem);
    }

    getProperties(num): StepComponentProperty {
        let prop = new StepComponentProperty();
        prop.circleHeight = '10px';
        prop.circleWidth = '10px';
        if ( num === 1 ) {
            prop.circleBackground = '#5A7BC3';
        }
        if ( num === 2 ) {
            prop.circleBackground = '#42C6F6';
            prop.circleBorder = '2px solid #5A7BC3';
        }
        return prop;
    }

    seeNoticeDetail() {
        // this.noticeDetail.emit();
        this.navCtrl.push("UploadingNoticeDetailPage", {noticeTime: this.noticeTime, attachmentId: this.attachmentId});
    }


    seeStopPowerApplication() {
        // this.stopPowerApplication.emit();
      this.navCtrl.push("StopPowerApplicationDetailPage", {userId: this.userId, chargeDetailId: this.chargeDetailId});
    }

    seePowerFailureDetail() {
        // this.powerFailureDetail.emit();
        this.navCtrl.push("UploadingPowerFailureDetailPage", {workData: this.workDate});
    }


    changerShow() {
        this.hidde = !this.hidde;
    }

    goImplementRrecord() {
      this.navCtrl.push("ImplementRecordDetailPage", {userId: this.userNo, chargeDetailId: this.chargeDetailId});
    }

    goApplyDetail() {
      this.navCtrl.push("ApplyResumptionDetailPage", {userId: this.userNo, chargeDetailId: this.chargeDetailId});
    }

}
